package cn.wolfcode.cms.util;

import cn.wolfcode.cms.domain.Permission;
import cn.wolfcode.cms.domain.SystemMenu;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.Iterator;
import java.util.List;

//用于过滤不符合要求菜单
public abstract  class SystemMenuUtil {
    public static final String MENU_IN_SESSION = "MENU_IN_SESSION";


    /**
     * 过滤菜单
     *   1>权限过滤
     *   2>空子菜单过滤
     * @param menus
     */
    public static void filterMenu(List<SystemMenu> menus){
        //过滤调用没有权限的菜单
        filterPermissionMenu(menus);

        //迭代删除没有儿子的父菜单
        Iterator<SystemMenu> iter = menus.iterator();
        while (iter.hasNext()){
            SystemMenu menu = iter.next();

            if(menu.getChildren() == null || menu.getChildren().size() == 0){
                iter.remove();
            }
        }
    }



    //过滤不符合要求菜单
    private static void filterPermissionMenu(List<SystemMenu> menus){
        //1:获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        //2:迭代判断当前菜单拥有的权限
        Iterator<SystemMenu> iter = menus.iterator();
        while (iter.hasNext()){
            //当前菜单
            SystemMenu menu = iter.next();
            //如果当前菜单不需要权限控制(不拥有permission对象)
            //如果没有, 跳过,菜单树直接显示该菜单
            Permission permission = menu.getPermission();
            if(permission != null){
                //如果当前菜单需要权限控制(拥有permission对象)
                //如果有,需要判断当前用户是否拥有该权限菜单
                if(!subject.isPermitted(permission.getResource())){
                    //拥有没有该菜单权限, 删除,菜单树不显示该菜单
                    iter.remove();
                }
            }
            //4:迭代判断子菜单是否拥有权限
            if(menu.getChildren() != null && menu.getChildren().size() > 0){
                //递归过滤子菜单
                filterPermissionMenu(menu.getChildren());
            }

        }

    }
}
